package com.music.hbox.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.music.domain.MusicList;
import com.music.hbox.dao.HboxDao;

@Repository
public class HboxDaoImpl implements HboxDao {
	@Autowired
	SessionFactory sessionFactory;
	@Override
	public void addMusic(String userid, String musicid) {
		String sql="insert into t_user_music(userid,musicid) values (:userid,:musicid)";
		SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sql);
		query.setParameter("userid", userid);
		query.setParameter("musicid", musicid);
		query.executeUpdate();
	}
	@Override
	public List<MusicList> findAllUserMusic(String userid) {
		List<MusicList> data=new ArrayList<>();
		String sql="select distinct(musicid) from t_user_music where userid=:userid";
		Session session = sessionFactory.getCurrentSession();
		SQLQuery sqlQuery = session.createSQLQuery(sql);
		sqlQuery.setParameter("userid", userid);
		List<String> musics = sqlQuery.list();
		for (String music : musics) {
			MusicList musicO = session.get(MusicList.class, music);
			if(musicO==null){
				continue;
			}
			data.add(musicO);
		}
		return data;
	}
	
	@Override
	public void deleteUserMusic(String userid, String musicid) {
		String sql="delete from t_user_music where userid=:userid and musicid=:musicid";
		SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sql);
		query.setParameter("userid", userid);
		query.setParameter("musicid", musicid);
		query.executeUpdate();
	}
	
	
	

}
